<?php

namespace Admin\Model;

use Think\Model;

class AdvertModel extends Model
{
    protected $insertFields = array('start_time', 'end_time', 'image', 'url');
    protected $updateFields = array('id', 'start_time', 'end_time', 'image', 'url');
    protected $_validate = array();

    public function search($pageSize = 20)
    {
        /**************************************** 搜索 ****************************************/
        $where = array();
        /************************************* 翻页 ****************************************/
        $count = $this->alias('a')->where($where)->count();
        $page = new \Think\Page($count, $pageSize);
        // 配置翻页的样式
        $page->setConfig('prev', '上一页');
        $page->setConfig('next', '下一页');
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $data['data'] = $this->alias('a')->where($where)->group('a.id')->limit($page->firstRow . ',' . $page->listRows)->select();
        return $data;
    }

    // 添加前
    protected function _before_insert(&$data, $option)
    {

        $data['start_time']=strtotime(I('POST.start_time'));
        $data['end_time']=strtotime(I('POST.end_time'));
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $ret = uploadOne('image', 'image', array());
            if ($ret['ok'] == 1) {
                $data['image'] = $ret['images'][0];
            } else {
                $this->error = $ret['error'];
                return FALSE;
            }
        }
    }

    // 修改前
    protected function _before_update(&$data, $option)
    {
        $id = $option['where']['id'];
        $data['start_time']=strtotime(I('POST.start_time'));
        $data['end_time']=strtotime(I('POST.end_time'));
        if (isset($_FILES['image']) && $_FILES['vpic']['image'] == 0) {

            $ret = uploadOne('image', 'image', array());
            if ($ret['ok'] == 1) {
                $data['image'] = $ret['images'][0];
            } else {
                $this->error = $ret['error'];
                return FALSE;
            }
        }
        $pic = M('advert')->field('image')->where(['id' => $id])->find();
        $ic = C('IMAGE_CONFIG');
        foreach ($pic as $v) {
            unlink($ic['rootPath'] . $v);
        }
    }

    // 删除前
    protected function _before_delete($option)
    {
        $id = $option['where']['id'];
        if (is_array($option['where']['id'])) {
            $this->error = '不支持批量删除';
            return FALSE;
        }
        $pic = M('advert')->field('image')->where(['id' => $id])->find();
        $ic = C('IMAGE_CONFIG');
        foreach ($pic as $v) {
            unlink($ic['rootPath'] . $v);
        }
    }
    /************************************ 其他方法 ********************************************/
}